<#
.SYNOPSIS
    Convert one docx file to pdf.
.DESCRIPTION
    Convert one docx file to pdf.
.PARAMETER Docxfile
    docx filename.
#>
param(
    [Parameter(Mandatory = $true)]
    [ValidateScript( {
        if (!(Test-Path $_ -PathType Leaf)) {
            throw "$_ is not existing!"
        } else {
            $true
        }
    })]
    [String] $Docxfile
)

# echo "$($Docxfile)"
# Write-Host "$($Docxfile)"
$Docxfile = Resolve-Path $Docxfile
# Write-Host "$($Docxfile)"
# $Docxfile = Resolve-Path $Docxfile | Get-Item -LiteralPath $_
$Docxf = Get-Item -LiteralPath $Docxfile
# Write-Host "$($Docxf.BaseName)"

# Swap out DOCX with PDF in the Filename
# $Name = ($Docxfile.Fullname).replace("docx","pdf")
$Name = "$($Docxf.DirectoryName)\$($Docxf.BaseName).pdf"
if (Test-Path $Name -PathType Leaf) {
    # Write-Error -Message "pdf file is existing!" -ErrorAction Stop
    throw "pdf file is existing!"
} else {
    $Word = NEW-OBJECT -COMOBJECT WORD.APPLICATION
    # $Word.Visible = $True
    # open a Word document, filename from the directory
    $Doc = $Word.Documents.Open($Docxf.fullname)

    # $document = $word_app.Documents.Open($_.FullName)
    # $pdf_filename = "$($_.DirectoryName)\$($_.BaseName).pdf"

    $Doc.saveas([ref] $Name, [ref] 17)

    $Doc.close()
    $Word.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Doc) | Out-Null
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word) | Out-Null
    Remove-Variable Doc,Word
}

Remove-Variable Docxf,Name
[gc]::collect()
[gc]::WaitForPendingFinalizers()
